function ajax(url) {
  return new Promise(function(resolve, reject) {
    var xhr = new XMLHttpRequest()
    xhr.open("GET", url)
    xhr.responseType = 'json'
    xhr.onload = function () {
      if(this.status === 200)
        resolve(this.response)
      else {
        reject(new Error(this.statusText))
      }
    }
    xhr.send()
  })
}
// 生成器函数
function * main () {
  try {
    const users = yield ajax('/api/users.json')
    console.log(users)
    
    const posts = yield ajax('/api/posts.json')
    console.log(posts)

    const urls = yield ajax('/api/urls.json')
    console.log(urls)
  } catch(e) {
    // 如果生成器函数中，发生了异常，会被生成器对象的throw方法捕获
    console.log(e)
  }
}

// 封装了一个生成器函数执行器
function co(main) {
  // 调用生成器函数得到一个生成器对象
  const generator = main()

  // 递归实现generator.next()的调用，直到done为true终止
  function handleResult(result) {
    if(result.done) return
    result.value.then(data=>{
      console.log(data)
      handleResult(generator.next(data))
    }, error => {
      g.throw(error)
    })
  }

  handleResult(generator.next())
}

co(main)

// Generator实现异步.js:42 {username: "yibo"}
// Generator实现异步.js:20 {username: "yibo"}
// Generator实现异步.js:42 {posts: "jiailing"}
// Generator实现异步.js:23 {posts: "jiailing"}
// Generator实现异步.js:42 {posts: "/api/posts.json", users: "/api/users.json"}
// Generator实现异步.js:26 {posts: "/api/posts.json", users: "/api/users.json"}